﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Point = OpenCvSharp.Point;

namespace Common.plate.common
{
    /// <summary>
    ///  // 绘制带中文的检测框(结果可视化)
    /// </summary>
    public class ResultVisualizer
    {
        public void DrawDetectionWithChinese1(Mat img, PlateInfo plateObj)
        {
            try
            {
                // 1. 绘制车牌边界框（绿色矩形）
                var bbox = plateObj.Bbox;
                var topLeft = new Point((int)bbox[0], (int)bbox[1]);
                var bottomRight = new Point((int)bbox[2], (int)bbox[3]);

                // 绘制矩形
                Cv2.Rectangle(img, topLeft, bottomRight, new Scalar(0, 255, 0), 2);

                // 准备文字 - 显示车牌号码和双层标识
                var text = plateObj.Text;

                // 将OpenCV Mat转换为Bitmap
                Bitmap bmp;
                using (var stream = new System.IO.MemoryStream())
                {
                    img.WriteToStream(stream);
                    bmp = new Bitmap(stream);
                }

                // 使用Graphics绘制中文
                using (var graphics = Graphics.FromImage(bmp))
                {
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

                    // 使用支持中文的字体
                    using (var font = new Font("微软雅黑", 12, FontStyle.Bold))
                    using (var brush = new SolidBrush(Color.Black))
                    using (var bgBrush = new SolidBrush(Color.FromArgb(255, 0, 255, 0)))
                    {
                        // 测量文字尺寸
                        var textSize = graphics.MeasureString(text, font);

                        // 计算文字位置
                        var textX = (int)bbox[0];
                        var textY = (int)bbox[1] - (int)textSize.Height - 5;

                        // 调整位置如果超出边界
                        if (textY < 0) textY = (int)bbox[1] + 25;

                        // 绘制文字背景
                        graphics.FillRectangle(bgBrush, textX, textY, textSize.Width, textSize.Height);

                        // 绘制文字
                        graphics.DrawString(text, font, brush, textX, textY);
                    }
                }

                // 将Bitmap转换回Mat
                using (var stream = new System.IO.MemoryStream())
                {
                    bmp.Save(stream, ImageFormat.Png);
                    stream.Position = 0;
                    var newImg = Mat.FromStream(stream, ImreadModes.Color);
                    newImg.CopyTo(img);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  绘制检测框错误: {ex.Message}");
            }
        }
    }
}
